package com.falcon.mojo.v1;

import com.falcon.domain.DependencyNode;
import com.falcon.mojo.AbsMojo;
import com.falcon.util.PathUtil;
import com.falcon.util.PomUtil;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.dom4j.Document;

import java.io.File;
import java.io.IOException;
import java.util.List;

/** 备份原pom、合并生成新的pom */
@Mojo(name = "pom-merge", defaultPhase = LifecyclePhase.CLEAN)
public class PomMergeMojo extends AbsMojo {

    public void execute() throws MojoExecutionException, MojoFailureException {

        // 备份原
//        this.backupPom();

        // 获取要合并的模块列表
        File[] modules = enableIncludeModules ? includeModules : getSubModules();

        // 获取所有子模块的依赖列表
        List<DependencyNode> needAddDependencies = getNeedAddDependencies(modules);

        // 获取汇总 pom.xml 的 dom 对象
        String currentPomFile = PathUtil.getPomPath(this.project);
        Document currentDocument = PomUtil.getDocument(currentPomFile);

        // 将子模块中的依赖列表添加到汇总 pom 的 dom 对象中
        PomUtil.appendDependencies(currentDocument, needAddDependencies);

        // 如果是覆盖源码中的 pom，则直接写入原 pom.xml 中
        getLog().info("准备覆盖原来的pom..");
        PomUtil.write(currentDocument, currentPomFile);
    }

    protected void backupPom() {
        this.checkTargetDir();

        String pomFile = PathUtil.getPomPath(this.project);
        String backupFile = PathUtil.getBackPomPath(this.project);
        try {
            FileUtils.copyFile(new File(pomFile), new File(backupFile));
        } catch (IOException e) {
            throw new RuntimeException("备份 pom 失败", e);
        }
        getLog().info("pom 备份成功，备份文件:" + pomFile);
    }

}
